<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';

import { ref } from 'vue';
import { useAccess } from '@vben/access';
import { downloadFileFromUrl } from '@vben/utils';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { Page, useVbenDrawer } from '@vben/common-ui';
import { Button, message, Tag, Dropdown, Menu } from 'ant-design-vue';
import { MdiAdd, MdiRefresh, MdiDelete, MdiDownload } from '@vben/icons';
import { getClientListApi, getSampleListApi, updateSampleDataApi, downloadTestFilesApi } from '#/api';

import sampleForm from './sample.vue';
import { confirmModal } from '#/components';
import testDataFormDrawer from './testdata.vue';
import { processedSampleArr } from './schemas/data';

interface RowType {
  clientName: string; // 委托单位
  contactPerson: string; // 委托人
  orderNo: string; // 委托单号
  sampleName: string; // 样品名称
  sampleNo: string; // 样品编号
  modelSpec: string; // 样品规格
  quantity: string; // 样品数量
  testItems: string; // 测试项目
  currentProgress: string; // 当前进度
  sampleStatus: string; // 样品状态
  receiver: string; // 收样人
  receiveDate: string; // 收样日期
  sampleHandling: string; // 样品处理方式
  analysisDate: string; // 分析日期
  tester: string; // 分析人
  processDate: string; // 处理日期
  processor: string; // 处理人
  reportNo: string; // 报告编号
  remarks: string; // 收样备注
  reportNotes: string; // 报告备注
  othersNotes: string; // 其他备注
}

const loadingV = ref(false); // 记录当前是否进入loading状态
const sampleFormRef = ref();
const { hasAccessByCodes } = useAccess();
// 使用ref定义颜色响应式对象
const colorMap = ref({
  样品接收: 'volcano',
  样品测试: 'cyan',
  报告编制: 'processing',
  报告审核: 'geekblue',
  报告批准: 'green',
  报告发放: 'success',
  完结: 'default',
});

const formOptions: VbenFormProps = {
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  commonConfig: {
    colon: true,
    lableWidth: '120',
    componentProps: {
      class: 'w-full',
    },
  },
  fieldMappingTime: [['receiveDate', ['startDate', 'endDate']]],
  schema: [
    {
      component: 'ApiSelect',
      componentProps: {
        // mode: 'multiple',
        placeholder: '请选择',
        allowClear: true,
        afterFetch: (data) => {
          if (data.length > 0) {
            return data.map((item: any) => ({
              label: item.clientName,
              value: item.clientName,
            }));
          } else {
            return [];
          }
        },
        api: getClientListApi,
      },
      label: '委托单位', // $t('page.auth.forgetPassword'),
      fieldName: 'clientName',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
        addonBefore: 'RT/JC-WT-',
      },
      fieldName: 'orderNo',
      label: '委托单编号',
    },
  ],
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: true,
  wrapperClass: 'grid-cols-3',
};

const gridOptions: VxeTableGridOptions<RowType> = {
  columns: [
    { fixed: 'left', field: 'checkbox', type: 'checkbox', title: '全选', width: 75 },
    { fixed: 'left', field: 'seq', type: 'seq', title: '序号', width: 50 },
    // { field: 'clientName', title: '委托单位', width: 200 },
    { field: 'contactPerson', title: '委托人', width: 100 },
    { field: 'orderNo', title: '委托单号', width: 180 },
    { field: 'sampleName', title: '样品名称', width: 150 },
    { field: 'sampleNo', title: '样品编号', width: 180 },
    { field: 'modelSpec', title: '样品规格', width: 150, slots: { default: 'modelSpecSlots' } },
    { field: 'quantity', title: '样品数量', width: 80 },
    { field: 'testItems', title: '测试项目', width: 300 },
    { field: 'currentProgress', title: '当前进度', slots: { default: 'currentProgress' }, width: 120 },
    // { field: 'sampleStatus', title: '样品状态', width: 200 },
    { field: 'receiver', title: '收样人', width: 100 },
    { field: 'receiveDate', title: '收样日期', width: 120, formatter: 'formatDate' },
    // { field: 'sampleHandling', title: '样品处理方式', width: 120 },
    { field: 'analysisDate', title: '分析日期', width: 120, formatter: 'formatDate' },
    { field: 'tester', title: '分析人', width: 100 },
    { field: 'processDate', title: '处理日期', width: 120, formatter: 'formatDate' },
    { field: 'processor', title: '取样/处理人', width: 100 },
    { field: 'reportNo', title: '报告编号', width: 180 },
    { field: 'remarks', title: '收样备注', width: 200 },
    // { field: 'reportNotes', title: '报告备注', width: 200 },
    // { field: 'othersNotes', title: '其他备注', width: 200 },
    { fixed: 'right', field: 'action', title: '操作', visible: true, slots: { default: 'action' }, width: 180 },
  ],
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const values = formValues;
        if (values.orderNo) {
          values.orderNo = 'RT/JC-WT-' + values.orderNo;
        }
        const result = await getSampleListApi({
          page: page.currentPage,
          pageSize: page.pageSize,
          ...values,
        });
        // 如果result.message不为ok或undefined，则使用message显示result.message
        if (result.message === '未查询到匹配的数据') {
          message.info(result.message);
          return [];
        } else if (result.message !== 'ok' && result.message !== undefined) {
          message.error(result.message);
        }

        // 转译数据，将processedSampleArr转换为对象
        const sampleMap = Object.fromEntries(processedSampleArr.map((item) => [item.label, item.value]));
        result.items = result.items.map((item: any) => {
          let sampleNameVal;
          if (item.sampleName.startsWith('[')) {
            if (JSON.parse(item.sampleName).length > 1) {
              sampleNameVal = sampleMap[JSON.parse(item.sampleName).join('-')].split('-')[1];
            } else {
              sampleNameVal = sampleMap[JSON.parse(item.sampleName)];
            }
          } else {
            sampleNameVal = item.sampleName;
          }

          return {
            ...item,
            sampleName: sampleNameVal,
            sampleHandling: item.sampleHandling ? '样品退回' : '检测单位自行处理',
          };
        });
        return result;
      },
    },
  },
  exportConfig: {},
  height: 'auto',
  // keepSource: true,
  showOverflow: false,
  pagerConfig: {},
  toolbarConfig: {
    export: true,
    refresh: true,
    refreshOptions: {
      code: 'reload',
    },
    search: true,
    zoom: true,
    custom: true,
  },
  customConfig: {
    mode: 'modal',
    checkMethod({ column }) {
      return !['checkbox', 'seq', 'orderNo', 'action'].includes(column.field);
    },
  },
  rowConfig: {
    isHover: true, // 鼠标悬停行时是否高亮显示
  },
  columnConfig: {
    resizeable: true, // 列宽可拖动
  },
  resizeableConfig: {
    isDblClickAutoWidth: true, // 双击列宽自动适应
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  // 默认显示搜索表单
  showSearchForm: true,
});

const [dataFormDrawer, dataFormDrawerApi] = useVbenDrawer({
  connectedComponent: testDataFormDrawer,
  destroyOnClose: true,
});

// 刷新并返回第一页
const handleReload = async () => {
  gridApi.reload();
};
// 数据填报
const handleDataForm = async (record: any) => {
  dataFormDrawerApi.setData({ record, gridApi }).open();
};
// 刷新当前页面
const handleRefresh = async () => {
  gridApi.query();
};
/*==================================函数过程=========================================*/
// 操作
const handleAction = async (action: 'new' | 'edit' | 'saveas' | 'delete' | 'download', record: any) => {
  try {
    loadingV.value = true;
    // 延迟0.5秒，确保全局loading生效，防止用户再次操作
    await new Promise((resolve) => setTimeout(resolve, 300));

    if (action === 'download') {
      // 处理下载
      if (!record) throw new Error('下载类型选择有误！');
      const selectedRows = await gridApi.grid.getCheckboxRecords();
      if (selectedRows.length > 0) {
        let downloadLists: string[] = [];
        for (const row of selectedRows) {
          downloadLists.push(row.sampleNo);
        }
        const res = await downloadTestFilesApi({
          type: record.split('_')[0],
          sampleNoArray: downloadLists,
          outputMode: record.split('_')[1],
        });
        // 已测试可以下载
        downloadFileFromUrl({
          source: res,
          target: '_self',
        });
        message.success('下载成功');
      } else {
        message.info('请至少选择一行数据');
      }
    } else if (action === 'delete') {
      let sampleNoTemp = [];
      if (record.sampleNo) {
        // 单行
        sampleNoTemp.push(record.sampleNo);
      } else {
        // 多行
        const selectedRows = await gridApi.grid.getCheckboxRecords();
        if (selectedRows.length > 0) {
          for (const row of selectedRows) {
            sampleNoTemp.push(row.sampleNo);
            // gridApi.grid.setCheckboxRow(row, false);
          }
        } else {
          message.info('请至少选择一行数据');
          return;
        }
      }

      const confirmRes = await confirmModal('提示', `确定删除以下编号的样品吗？\n${sampleNoTemp.join('\n')}`);
      if (confirmRes) {
        const res = await updateSampleDataApi({
          action: 'delete',
          data: JSON.stringify(sampleNoTemp),
        });
        if (res.code === 0 || res.code === 1) {
          message.success(res.msg);
          gridApi.query();
        } else {
          message.error('删除失败');
          gridApi.query();
        }
      }
    } else {
      // 处理其他操作
      sampleFormRef.value.setData({
        record,
        whichAction: action,
        gridApi,
      });
      sampleFormRef.value.open();
    }
  } catch (error) {
    message.error(`操作失败：${error.message}`);
  } finally {
    await new Promise((resolve) => setTimeout(resolve, 300));
    loadingV.value = false;
  }
};

const handleDropDownClick = (e) => {
  handleAction('download', e.key || null);
};
</script>
<template>
  <Page v-loading="loadingV" auto-content-height>
    <Grid>
      <template #modelSpecSlots="{ row }">
        <div v-html="row.modelSpec"></div>
      </template>
      <template #action="{ row }">
        <Button v-if="hasAccessByCodes(['msdsEdit'])" class="px-1" type="link" @click="handleAction('edit', row)"
          >编辑</Button
        >
        <Button v-if="hasAccessByCodes(['msdsEdit'])" class="px-1" type="link" @click="handleAction('saveas', row)"
          >另存</Button
        >
        <Button
          v-if="hasAccessByCodes(['msdsEdit'])"
          class="px-1"
          style="color: darkviolet"
          type="link"
          @click="handleDataForm(row)"
          >数据</Button
        >
        <Button
          v-if="hasAccessByCodes(['msdsDelete'])"
          class="px-1"
          danger
          type="link"
          @click="handleAction('delete', row)"
          >删除</Button
        >
      </template>
      <template #currentProgress="{ row }">
        <Tag :bordered="false" :color="colorMap[row.currentProgress] || 'error'">
          {{ row.currentProgress }}
        </Tag>
      </template>
      <template #toolbar-actions>
        <Button
          v-if="hasAccessByCodes(['msdsNew'])"
          class="mr-2 flex items-center justify-center"
          type="primary"
          @click="handleAction('new', {})"
        >
          <!-- 20像素大小的图标 -->
          <MdiAdd class="size-4" />
          新增
        </Button>
        <Button
          class="mr-2 flex items-center justify-center"
          type="primary"
          style="background-color: #0bd092"
          @click="handleReload"
        >
          <MdiRefresh class="size-4" />
          刷新
        </Button>
        <Button
          v-if="hasAccessByCodes(['msdsDelete'])"
          class="mr-2 flex items-center justify-center"
          type="primary"
          danger
          @click="handleAction('delete', {})"
        >
          <MdiDelete class="size-4" />
          删除
        </Button>
        <Dropdown :trigger="['click']" class="mr-2" @click.prevent>
          <template #overlay>
            <Menu @click="handleDropDownClick">
              <Menu.SubMenu key="sub1" title="下载报告">
                <Menu.Item key="report_OnlyDocx">docx文件</Menu.Item>
                <Menu.Item key="report_OnlyPdf">pdf文件</Menu.Item>
                <Menu.Item key="report_All">均下载</Menu.Item>
              </Menu.SubMenu>
              <Menu.SubMenu key="sub2" title="下载委托单" disabled>
                <Menu.Item key="order_OnlyDocx">docx文件</Menu.Item>
                <Menu.Item key="order_OnlyPdf">pdf文件</Menu.Item>
                <Menu.Item key="order_All">均下载</Menu.Item>
              </Menu.SubMenu>
            </Menu>
          </template>
          <Button type="primary" class="flex items-center justify-center" style="background-color: #ff9940">
            <MdiDownload class="size-4" />
            下载
          </Button>
        </Dropdown>
      </template>
    </Grid>
    <sampleForm ref="sampleFormRef" />
    <dataFormDrawer />
  </Page>
</template>
